<?php
	namespace plugins\word\controller;

	use cmf\controller\PluginAdminBaseController;
	use think\Db;
	use tree\Tree;
	use app\common\lib\AccessAuthorization;

class AdminIndexController extends PluginAdminBaseController{
	protected function _initalize(){
		parent::_initalize();
		$adminId = cmf_et_current_admin_id();
		if(!empty($adminId)){
			$this->assign("admin_id",$adminId);
		}
	}

	/**
	 * 任务管理模块 菜单注解
	 * @adminMenu(
	 * 		'name'		=>	'文档管理',
	 * 		'parent'	=>	'admin/Plugin/default',
	 * 		'display'	=>	true,
	 * 		'hasView'	=>	true,
	 * 		'order'		=>	9999,
	 * 		'icon'		=>	'',
	 * 		'remark'	=>	'文档管理',
	 * 		'param'		=>	''
	 * )
	 */
	public function index(){
		$param = $this->request->get();
		if(!empty($param['id'])){
			$id = $param['id'];
		}else{
			$id = 0;
		}
		$this->assign('id',$id);


		/*tree设置*/
		$tree = new Tree();
		$tree->icon = ['&nbsp;&nbsp;&nbsp;&nbsp│', '&nbsp;&nbsp;&nbsp;&nbsp;├', '&nbsp;&nbsp;&nbsp;&nbsp;└'];
		$list = $this->getList(cmf_get_current_admin_id());
		foreach ($list as $key => &$value) {
			if($value['type'] == '1'){
				$value['icon'] = "📁";
			}else{
				$value['disabled'] = "";
				$value['icon'] = "📄";
			}
			
			if($value['id'] == $id){
				$value['selected'] = "selected='selected'";
			}

		}
		$str = "<option value=\$id \$selected>\$spacer \$icon \$name</option>";
		/*tree设置*/

		//内容放入
		$tree->init($list);
		//tree生成
		$select =  $tree->getTree('0',$str);

		$this->assign('select',$select);
		return $this->fetch();
	}

	//得到对应的文章内容
	public function wordContent(){
		$param = $this->request->get();
		//权限判断用
		$uid = cmf_get_current_admin_id();
		$info = '';
		//主页的搜索
		if($param['id'] == 0){
			$parents = $this->getList($uid,0,$param['id']);
			$info['content'] = '';
				//要显示的内容
			foreach ($parents as $key => $value) {
				$info['content'] .= "<li class='layui-timeline-item' value='".$value['id']."' ondblclick='tz(".$value['id'].")'>";
				$info['content'] .= "<div class='layui-timeline-content layui-text'>";
				$info['content'] .= "<a>";
				if($value['type'] == '1'){
					$info['content'] .= "📁";
				}else{
					$info['content'] .= "📄";
				}
				$info['content'] .= $value['name'];
				$info['content'] .= "</a>";
				//权限检测
				$return = $this->wordCheck($uid,$value['id']);
				if($return['edit'] == 1){
					$info['content'] .= "<i class='layui-icon layui-icon-edit' onclick='edit(".$value['id'].",".$value['type'].")'></i>";
				}
				if($return['del'] == 1){
					$info['content'] .= "<i class='layui-icon layui-icon-delete' onclick='del(".$value['id'].")'></i>";
				}
				$info['content'] .= "</div>";
				$info['content'] .= "</li>";
			}	

			$info['content'] .= "<script type='text/javascript'>sort();</script>";	

			return json(['type'=>'success','msg'=>'查询成功','info'=>$info]);	
		}

		$info = db('word')->where(['id'=>$param['id'],'status'=>0])->find();
		if($info){
			//文档创建人名字获取
			$info['uname'] = $this->uidGetName($info['create_user']);

			$return = $this->wordCheck($uid,$param['id']);
			$info['del'] = $return['del'];
			$info['edit'] = $return['edit'];
			// //编辑权限判断
			// if($info['create_user'] == $uid){
			// 	$info['edit'] = 1;
			// }else{
			// 	$info['edit'] = 0;
			// }

			// //自身以下的权限
	  //   	$limit = new AccessAuthorization();
	  //   	//当前用户下属
	  //   	$access = $limit->getAccessibleIdsByUserId($uid);
	  //   	$search = array_search($info['create_user'],$access);
	  //   	if($search !== false){
	  //   		$info['edit'] = 1;
	  //   	}

	  //   	if($this->delCheck($info['id'])){
	  //   		//有子级，不可删除
	  //   		$info['del'] = 0;
	  //   	}else{
	  //   		//无子级，可以删除
	  //   		$info['del'] = 1;
	  //   	}

			//选中文件是文件夹的情况
			if($info['type'] == 1){
				//得到子文件
				$parents = $this->getList($uid,0,$info['id']);
				$info['content'] = '';
				// $info['content'] .= "<ul id='sortable'>";
				//要显示的内容
				foreach ($parents as $key => $value) {
					$info['content'] .= "<li class='layui-timeline-item' value='".$value['id']."' ondblclick='tz(".$value['id'].")'>";
					$info['content'] .= "<div class='layui-timeline-content layui-text'>";
					$info['content'] .= "<a>";
					if($value['type'] == '1'){
						$info['content'] .= "📁";
					}else{
						$info['content'] .= "📄";
					}
					$info['content'] .= $value['name'];
					$info['content'] .= "</a>";
					//权限检测
					$return = $this->wordCheck($uid,$value['id']);
					if($return['edit'] == 1){
						$info['content'] .= "<i class='layui-icon layui-icon-edit' onclick='edit(".$value['id'].",".$value['type'].")'></i>";
						//排序功能渲染
						$info['content'] .= "<script type='text/javascript'>sort();</script>";
					}
					if($return['del'] == 1){
						$info['content'] .= "<i class='layui-icon layui-icon-delete' onclick='del(".$value['id'].")'></i>";
					}
					$info['content'] .= "</div>";
					$info['content'] .= "</li>";

					$info['content'] .= "<script type='text/javascript'>sort();</script>";	

				// $info['content'] .= "</ul>";
				}
			}else{
				//文本化
				$info['content'] = html_entity_decode($info['content']);
			}

			//$info = autoHtmlspecialcharsDecode($info);
			
			return json(['type'=>'success','msg'=>'查询成功','info'=>$info]);
		}else{
			return json(['type'=>'error','msg'=>'查询出错']);
		}	
	}

	//添加文档界面
	public function addWordPage(){
		$tree = new Tree();
		$tree->icon = ['&nbsp;&nbsp;&nbsp;&nbsp│', '&nbsp;&nbsp;&nbsp;&nbsp;├', '&nbsp;&nbsp;&nbsp;&nbsp;└'];
		//查询仅显示目录
		// $list = db('word')->where(['type'=>1])->select()->toArray();
		$list = $this->getList(cmf_get_current_admin_id(),1);
		foreach ($list as $key => &$value) {
			if($value['type'] == '1'){
				// $value['disabled'] = "disabled='disabled'";
				$value['icon'] = "📁";
			}else{
				$value['disabled'] = "";
				$value['icon'] = "📄";
			}
		}				
		$str = "<option value=\$id \$selected>\$spacer \$icon \$name</option>";
		$tree->init($list);
		$select =  $tree->getTree('0',$str);
		$this->assign('select',$select);		
		return $this->fetch();
	}

	//添加文档
	public function addWord(){
		$param = $this->request->post();
		$param['type'] = 2;
		$param['create_time'] = time();
		$param['create_user'] = cmf_get_current_admin_id();
		//vid即私有查看人员的数组
		if($param['private'] == 1 && !empty($param['vid'])){
			$vid = $param['vid'];
		}

		//新增入队尾
		$sort = db('word')->field('sort')->where(['parent_id'=>$param['parent_id']])->order("sort desc")->limit(1)->find();
		$param['sort'] = $sort['sort']+1;

		//添加主表并返回id
		$return = db('word')->insertGetId($param);
		//当选择了私有查看的情况
		if($return){
			if(!empty($vid)){
				//私有人员
				$private = [];
				//遍历所有人员
				foreach ($vid as $key => &$value) {
					$this->setPrivate($return,$value);
					$private[$key]['word_id'] = $return;
					$private[$key]['insert_id'] = cmf_get_current_admin_id();
					$private[$key]['reader_id'] = $value;
				}
				db('word_private')->insertAll($private);
			}			
			return json(['type'=>'success','msg'=>'添加成功','id'=>$return]);
		}else{
			return json(['type'=>'error','msg'=>'添加未生效']);
		}			
	}

	//修改文档界面
	public function editWordPage(){
		$param = $this->request->get();
		//得到选中的信息
		$info = db('word')->where(['id'=>$param['id']])->find();
		$info['vid']['vname'] = "";
		$info['vid']['vid'] = "";
		//文本化
		$info['content'] = html_entity_decode($info['content']);
		//检索私有查看人员
		if($info['private'] == 1){
			$list = db('word_private')->field("reader_id")->where(['word_id'=>$info['id']])->select()->toArray();

			foreach ($list as $k => &$v) {
				$info['vid']['vname'] .= $this->uidGetName($v['reader_id']).",";
				$info['vid']['vid'] .= "'".$v['reader_id']."',";
			}
			$info['vid']['vname'] = substr($info['vid']['vname'],0,strlen($info['vid']['vname'])-1);
			$info['vid']['vid'] = substr($info['vid']['vid'],0,strlen($info['vid']['vid'])-1);
		}		
		$this->assign('info',$info);

		//目录添加
		$tree = new Tree();
		$tree->icon = ['&nbsp;&nbsp;&nbsp;&nbsp│', '&nbsp;&nbsp;&nbsp;&nbsp;├', '&nbsp;&nbsp;&nbsp;&nbsp;└'];
		//查询仅显示目录
		// $list = db('word')->where(['type'=>1])->select()->toArray();
		$list = $this->getList(cmf_get_current_admin_id(),1);
		foreach ($list as $key => &$value) {
			//默认的父类
			if($info['parent_id'] == $value['id']){
				$value['selected'] = "selected='selected'";
			}			
			if($value['type'] == '1'){
				// $value['disabled'] = "disabled='disabled'";
				$value['icon'] = "📁";
			}else{
				$value['disabled'] = "";
				$value['icon'] = "📄";
			}
		}

		$str = "<option value=\$id \$selected>\$spacer \$icon \$name</option>";
		$tree->init($list);
		$select =  $tree->getTree('0',$str);
		$this->assign('select',$select);
		return $this->fetch();
	}

	//修改文档
	public function editWord(){
		$param = $this->request->post();
		$uid = cmf_get_current_admin_id();
		//修改
		$return = db('word')
			->where(['id'=>$param['id']])
			->update(['parent_id'=>$param['parent_id'],'name'=>$param['name'],'private'=>$param['private'],'content'=>$param['content']]);
		//私有且不为空
		if(!empty($param['vid']) && $param['private'] == 1){
			db('word_private')->where(['word_id'=>$param['id']])->delete();
			$list = [];
			foreach ($param['vid'] as $key => $value) {
				$this->setPrivate($param['id'],$value);
				$list[$key]['word_id'] = $param['id'];
				$list[$key]['insert_id'] = $uid;
				$list[$key]['reader_id'] = $value;
			}
			db('word_private')->insertAll($list);
			$return = true;
		//私有且无可读取人员
		}else if(empty($param['vid']) && $param['private'] == 1){
			db('word_private')->where(['word_id'=>$param['id']])->delete();
			$return = true;
		}
		if($return){
			return json(['type'=>'success','msg'=>'编辑成功']);
		}else{
			return json(['type'=>'error','msg'=>'修改内容已保存']);
		}	
	}

	//修改目录页面
	public function editFilePage(){
		$param = $this->request->get();
		$info = db('word')->where(['id'=>$param['id']])->find();
		$info['vid']['vname'] = "";
		$info['vid']['vid'] = "";
		//检索私有查看人员
		if($info['private'] == 1){
			$list = db('word_private')->field("reader_id")->where(['word_id'=>$info['id']])->select()->toArray();

			foreach ($list as $k => &$v) {
				$info['vid']['vname'] .= $this->uidGetName($v['reader_id']).",";
				$info['vid']['vid'] .= "'".$v['reader_id']."',";
			}
			$info['vid']['vname'] = substr($info['vid']['vname'],0,strlen($info['vid']['vname'])-1);
			$info['vid']['vid'] = substr($info['vid']['vid'],0,strlen($info['vid']['vid'])-1);
		}
		$this->assign('info',$info);

		$tree = new Tree();
		$tree->icon = ['&nbsp;&nbsp;&nbsp;&nbsp│', '&nbsp;&nbsp;&nbsp;&nbsp;├', '&nbsp;&nbsp;&nbsp;&nbsp;└'];
		//查询仅显示目录
		// $list = db('word')->where(['type'=>1])->select()->toArray();
		$list = $this->getList(cmf_get_current_admin_id(),1);	
		foreach ($list as $key => &$value) {
			if($info['parent_id'] == $value['id']){
				$value['selected'] = "selected='selected'";
			}
			if($value['type'] == '1'){
				// $value['disabled'] = "disabled='disabled'";
				$value['icon'] = "📁";
			}else{
				$value['disabled'] = "";
				$value['icon'] = "📄";
			}
			
		}
		$str = "<option value=\$id \$selected>\$spacer \$icon \$name</option>";
		$tree->init($list);
		$select =  $tree->getTree('0',$str);
		$this->assign('select',$select);	
		return $this->fetch();
	}

	//修改目录
	public function editFile(){
		$param = $this->request->post();
		$uid = cmf_get_current_admin_id();
		$return = db('word')
			->where(['id'=>$param['id']])
			->update(['parent_id'=>$param['parent_id'],'name'=>$param['name'],'private'=>$param['private']]);
		//私有且不为空
		if(!empty($param['vid']) && $param['private'] == 1){
			db('word_private')->where(['word_id'=>$param['id']])->delete();
			$list = [];
			foreach ($param['vid'] as $key => $value) {
				$this->setPrivate($param['id'],$value);
				$list[$key]['word_id'] = $param['id'];
				$list[$key]['insert_id'] = $uid;
				$list[$key]['reader_id'] = $value;
			}
			db('word_private')->insertAll($list);
			$return = true;
		//私有且无可读取人员
		}else if(empty($param['vid']) && $param['private'] == 1){
			db('word_private')->where(['word_id'=>$param['id'],'insert_id'=>$uid])->delete();
			$return = true;
		}
		if($return){
			return json(['type'=>'success','msg'=>'编辑成功']);
		}else{
			return json(['type'=>'error','msg'=>'编辑未生效']);
		}	
	}

	//添加目录页面
	public function addFilePage(){
		$tree = new Tree();
		$tree->icon = ['&nbsp;&nbsp;&nbsp;&nbsp│', '&nbsp;&nbsp;&nbsp;&nbsp;├', '&nbsp;&nbsp;&nbsp;&nbsp;└'];
		//查询仅显示目录
		// $list = db('word')->where(['type'=>1])->select()->toArray();
		$list = $this->getList(cmf_get_current_admin_id(),1);		
		foreach ($list as $key => &$value) {
			if($value['type'] == '1'){
				// $value['disabled'] = "disabled='disabled'";
				$value['icon'] = "📁";
			}else{
				$value['disabled'] = "";
				$value['icon'] = "📄";
			}
			
		}				
		$str = "<option value=\$id \$selected>\$spacer \$icon \$name</option>";
		$tree->init($list);
		$select =  $tree->getTree('0',$str);
		$this->assign('select',$select);		
		return $this->fetch();
	}

	//添加新的目录
	public function addFile(){
		$param = $this->request->post();
		$param['type'] = 1;
		$param['create_time'] = time();
		$param['create_user'] = cmf_get_current_admin_id();
		$vid = '';
		if($param['private'] == 1 && !empty($param['vid'])){
			$vid = $param['vid'];
		}
		unset($param['vid']);

		//新增入队尾
		$sort = db('word')->field('sort')->where(['parent_id'=>$param['parent_id']])->order("sort desc")->limit(1)->find();
		$param['sort'] = $sort['sort']+1;

		$return = db('word')->insertGetId($param);
		if($return){
			if(!empty($vid)){
				$private = [];
				foreach ($vid as $key => &$value) {
					$this->setPrivate($return,$value);
					$private[$key]['word_id'] = $return;
					$private[$key]['insert_id'] = cmf_get_current_admin_id();
					$private[$key]['reader_id'] = $value;
				}
				db('word_private')->insertAll($private);
			}
			return json(['type'=>'success','msg'=>'添加成功','id'=>$return]);
		}else{
			return json(['type'=>'error','msg'=>'添加未生效']);
		}		
	}

    //人员列表
    public function userList(){
    	$param = $this->request->get();
    	$vid = $param['vid'];
    	$arr = explode(",", $vid);
    	$list = db('user')->field('id,user_login')->select()->toArray();
    	$array = [];
    	foreach ($list as $key => &$value) {
    		foreach ($arr as $k => $v) {
    			if($v == $value['id']){
    				$value['checked'] = true;
					$array[] = $list[$key];
					unset($list[$key]);  
					break;  				
    			}else{
    				$value['checked'] = false;
    			}
    		}
    	}
    	$array = array_merge($array,$list);
    	$this->assign('list',$array);
    	return $this->fetch();
    }

    //排序
    public function sort(){
    	$param = $this->request->post();
    	$list = $param['sort'];
    	foreach ($list as $key => $value) {
    		$return = db('word')->where(['id'=>$value])->update(['sort'=>$key]);
    	}
    }

    //检测父级状态
    public function checkParent(){
    	$param = $this->request->post();
    	$parent = db('word')->field('private')->where(['id'=>$param['id']])->find();
    	return $parent['private'];
    }

    //删除功能
    public function del(){
    	$param = $this->request->post();
    	//得到文章所属用户
    	$info = db('word')->field('create_user,parent_id')->where(['id'=>$param['id']])->find();
    	//权限判断用
		$uid = cmf_get_current_admin_id();
		//自身以下的权限
    	$limit = new AccessAuthorization();
    	//当前用户下属
    	$access = $limit->getAccessibleIdsByUserId($uid);
    	$search = array_search($info['create_user'],$access);
    	//所属正确,进行删除
    	if($search !== false){
    		$return = db('word')->where(['id'=>$param['id']])->update(['status'=>1]);
    		if($return){
    			return json(['type'=>'success','code'=>200,'msg'=>'删除成功','parent'=>$info['parent_id']]);
    		}else{
    			return json(['type'=>'error','code'=>-2,'msg'=>'删除失败']);
    		}
    	}else{
    		return json(['type'=>'error','code'=>-2,'msg'=>'无操作权限']);
    	}
    }

    //传入用户id与文件id查询权限
    private function wordCheck($uid,$id){
    	//搜索创建人
    	$find = db('word')->field("create_user")->where(['id'=>$id])->find();
    	$return = [];
		//通过创建人及你想编辑权限判断
		if($find['create_user'] == $uid){
			$return['edit'] = 1;
		}else{
			$return['edit'] = 0;
		}

		//自身以下的权限
    	$limit = new AccessAuthorization();
    	//当前用户下属
    	$access = $limit->getAccessibleIdsByUserId($uid);
    	$search = array_search($find['create_user'],$access);
    	if($search !== false){
    		$return['edit'] = 1;
    	}

    	//删除的检测
    	//没有编辑权限也没有删除权限
    	if($return['edit'] == 0 ){
    		$return['del'] = 0;
    		return $return;
    	}

    	$del = db('word')->field('id')->where(['parent_id'=>$id,'status'=>0])->select()->toArray();
    	if($del){
    		//有子级,不可删除
    		$return['del'] = 0;
    	}else{
    		//无子级.可删除
    		$return['del'] = 1;
    	}

    	return $return;
    }


    //得到列表,
    //type1为file 2为word,有这个参数则搜索指定类型
    //pid有的情况下搜索指定id下的子元素
    private function getList($uid,$type=0,$pid=null){
    	$where = '';

    	$where .= '(';
    	//公有
    	$where .= 'private = 0';

    	//自身创建的
    	$where .= ' or create_user = '.$uid;
    	
    	//私有
    	$private = db('word_private')->field("word_id")->where(['reader_id'=>$uid])->select()->toArray();
		if($private){
			foreach ($private as $key => $value) {
				$where .= " or id = ".$value['word_id'];
			}
		}

		//权限
    	$limit = new AccessAuthorization();
    	$access = $limit->getAccessibleIdsByUserId($uid);
    	foreach ($access as $key => $value) {
    		$where .= " or create_user = ".$value;
    	}


		$where .= ')';

		$where .= " and status = 0";

		//指定文件类型时
    	if($type != 0){
    		$where .= " and type = ".$type;
    	}

    	//指定id文件下的文件
    	if(!is_null($pid)){
    		$where .= " and parent_id = ".$pid;
    	}
    	//搜索对应条件的结果
    	$list = db('word')->field("id,type,parent_id,name")->where($where)->order('sort')->select()->toArray();
    	return $list;
    }

    //用户id获得用户名
    private function uidGetName($uid){
    	$info = db('user')->field('user_login')->where(['id'=>$uid])->find();
    	$uname = $info['user_login'];
    	if($uname){
    		return $uname;
    	}
    	return '';
    }

    //新建添加私有时输入文档id，开通全部的权限
    private function setPrivate($wordId,$reader_id){
    	$parent = db('word')->field("parent_id,private")->where(['id'=>$wordId])->find();

    	if($parent['parent_id'] != 0){
    		$this->setPrivate($parent['parent_id'],$reader_id);
    	}else{
    		return true;
    	}

    	if($parent['private'] == 1){
    		$uid = cmf_get_current_admin_id();

    		$check = db('word_private')->where(['word_id'=>$parent['parent_id'],'reader_id'=>$reader_id])->find();

    		if(!$check){
    			db('word_private')->insert(['word_id'=>$parent['parent_id'],'insert_id'=>$uid,'reader_id'=>$reader_id]);
    		}

    	}
    }

}

?>